//app.js
import {fetch} from './utils/index.js';
App({
    onLaunch: function() {
        // this.login();
    },

    login: function(cb) {
        const that = this;
        wx.login({
            success: function(res) {

                if (res.errMsg === 'login:ok') {

                    let result = fetch.post("weixin/login", {code: res.code});

                    result.then(function(res) {

                        const third_session = res.access_token;
                        wx.setStorageSync('WeixinAppThirdSession', third_session);
                        wx.getUserInfo({
                            success: function(user) {
                                that.globalData.userInfo = user.userInfo;
                                fetch.post("weixin/update_user_info", {user_info: user.userInfo}).then(function(res) {
                                    if (cb) 
                                        cb();
                                    }
                                );
                            },
                            fail: function() {
                                if (cb) 
                                    cb();
                                }
                            });

                    });
                }
            }
        });
    },

    getUserInfo: function(cb) {
        var that = this
        if (this.globalData.userInfo) {
            typeof cb == "function" && cb(this.globalData.userInfo)
        } else {
            //调用登录接口
            wx.getUserInfo({
                withCredentials: false,
                success: function(res) {
                    that.globalData.userInfo = res.userInfo
                    typeof cb == "function" && cb(that.globalData.userInfo)
                }
            })
        }
    },

    globalData: {
        userInfo: null
    }
})
